const city = require('../../utils/city.js');
const cityObjs = require('../../utils/city.js');
const appInstance = getApp();
Page({
  data: {
    searchLetter: [],
    showLetter: "",
    winHeight: 0,
    cityList: [],
    isShowLetter: false,
    scrollTop: 0,//置顶高度
    scrollTopId: '',//置顶id
    city: "定位中",
    currentCityCode: '',
    keys: "PCZBZ-6Y3W6-HVVSM-E22YX-JTSYO-QJBZD",
    hotcityList: [{ cityCode: 110000, city: '北京市' }, { cityCode: 310000, city: '上海市' }, { cityCode: 440100, city: '广州市' }, { cityCode: 440300, city: '深圳市' }, { cityCode: 330100, city: '杭州市' }, { cityCode: 320100, city: '南京市' }, { cityCode: 420100, city: '武汉市' }, { cityCode: 120000, city: '天津市' }, { cityCode: 610100, city: '西安市' },],
    commonCityList: [{ cityCode: 110000, city: '北京市' }, { cityCode: 310000, city: '上海市' }],
    countyList: [{ cityCode: 110000, county: 'X区' }, { cityCode: 310000, county: 'X区' }, { cityCode: 440100, county: 'X区' }, { cityCode: 440300, county: 'X区' }, { cityCode: 330100, county: 'X县' }, { cityCode: 320100, county: 'X县' }, { cityCode: 420100, county: 'X县' }],
    inputName: '',
    completeList: [],
    county: '',
    condition: false,
  },
  onLoad: function () {
    const searchLetter = city.searchLetter;
    const cityList = city.cityList();
    const sysInfo = wx.getSystemInfoSync();
    const winHeight = sysInfo.windowHeight;
    const itemH = winHeight / searchLetter.length;
    let tempArr = [];

    searchLetter.map(
      (item, index) => {
        let temp = {};
        temp.name = item;
        temp.tHeight = index * itemH;
        temp.bHeight = (index + 1) * itemH;
        tempArr.push(temp)
      }
    );

    this.setData({
      winHeight: winHeight,
      itemH: itemH,
      searchLetter: tempArr,
      cityList: cityList
    });

    this.getLocation();

  },

  clickLetter: function (e) {
    const showLetter = e.currentTarget.dataset.letter;
    this.setData({
      toastShowLetter: showLetter,
      isShowLetter: true,
      scrollTopId: showLetter,
    })

    const that = this;
    setTimeout(function () {
      that.setData({
        isShowLetter: false
      })
    }, 500)
  },
  //选择城市
  bindCity: function (e) {
    this.setData({
      condition: true,
      city: e.currentTarget.dataset.city,
      currentCityCode: e.currentTarget.dataset.code,
      scrollTop: 0,
      completeList: [],
    })
    this.selectCounty()

    appInstance.globalData.defaultCity = this.data.city
    appInstance.globalData.defaultCounty = ''
  },

  bindCounty: function (e) {
    this.setData({ county: e.currentTarget.dataset.city })
    appInstance.globalData.defaultCounty = this.data.county
    console.log('你所选的城市是：' + appInstance.globalData.defaultCity + appInstance.globalData.defaultCounty);

    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];  //当前页面
    var prevPage = pages[pages.length - 2]; //上一个页面
    prevPage.setData({
      sellerList: [],
      area_human: 0,
      currentCity: appInstance.globalData.defaultCounty
    });
    appInstance.globalData.currentCity = appInstance.globalData.defaultCounty;
    appInstance.globalData.currentCode = e.currentTarget.dataset.code;
    prevPage.getMallSeller(appInstance.globalData.latitude, appInstance.globalData.longitude, appInstance.globalData.currentCode,1);

    wx.navigateBack({//返回
      delta: 1
    });
  },

  //点击热门城市回到顶部
  hotCity: function () {
    this.setData({
      scrollTop: 0,
    })
  },
  selectCounty: function () {
    let code = this.data.currentCityCode
    let keys = this.data.keys
    const that = this;
    that.setData({
      countyList: []
    });
    wx: wx.showLoading({
      title: '正在加载中',
    })
    appInstance.HttpPostSend('/mall/get_location_district', { code: code }, function (res) {
      wx.hideLoading();
      var re_data = res;
      if (re_data.code > 0) {
        that.setData({
          countyList: res.list
        })
        // console.log(res)
      } else {
        wx.showModal({
          title: '提示',
          content: '获取定位失败，请手动选择地区',
          showCancel: false,
          success: function (res) {
            if (res.cancel) {

            } else if (res.confirm) {
              that.location_data()
            }
          }
        })
      }
    });
    // wx.request({
    //   url: `https://apis.map.qq.com/ws/district/v1/getchildren?&id=${code}&key=${keys}`,
    //   success: function (res) {

    //   },
    //   fail: function () {
    //     console.log("请求失败，请重试");
    //   }
    // })
  },
  location_data: function (uid) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
            showCancel: false,
            success: function (res) {
              if (res.cancel) {

                wx.showToast({
                  title: '授权失败',
                  icon: 'success',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      that.getLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入


        }
        else { //授权后默认加载


        }
      }
    })
  },

  getLocation: function () {
    this.setData({
      county: ''
    })
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        appInstance.globalData.latitude = res.latitude
        appInstance.globalData.longitude = res.longitude
        let keys = that.data.keys
        appInstance.HttpPostSend('/mall/get_location', { latitude: latitude, longitude: longitude }, function (res) {
          // wx.hideLoading();
          var re_data = res;
          if (re_data.code > 0) {
            that.setData({
              currentCityCode: re_data.city_code,
              currentCity: re_data.district
            })
            that.setData({
              city: re_data.city,
              city_code: re_data.city_code,
              county: re_data.district
            })
            that.selectCounty();
          } else {
            wx.showModal({
              title: '提示',
              content: '获取定位失败，请手动选择地区',
              showCancel: false,
              success: function (res) {
                if (res.cancel) {


                } else if (res.confirm) {

                  return false;
                }
              }
            })
          }

        });

      }
    })
  },
  bindBlur: function (e) {
    this.setData({
      inputName: ''
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      inputName: e.detail.value
    })
    this.auto()
  },
  auto: function () {
    let inputSd = this.data.inputName.trim()
    let sd = inputSd.toLowerCase()
    let num = sd.length
    const cityList = cityObjs.cityObjs
    let finalCityList = []

    let temp = cityList.filter(
      item => {
        let text = item.short.slice(0, num).toLowerCase()
        return (text && text == sd)
      }
    )
    let tempShorter = cityList.filter(
      itemShorter => {
        if (itemShorter.shorter) {
          let textShorter = itemShorter.shorter.slice(0, num).toLowerCase()
          return (textShorter && textShorter == sd)
        }
        return
      }
    )

    let tempChinese = cityList.filter(
      itemChinese => {
        let textChinese = itemChinese.city.slice(0, num)
        return (textChinese && textChinese == sd)
      }
    )

    if (temp[0]) {
      temp.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        }
      )
      this.setData({
        completeList: finalCityList,
      })
    } else if (tempShorter[0]) {
      tempShorter.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        }
      );
      this.setData({
        completeList: finalCityList,
      })
    } else if (tempChinese[0]) {
      tempChinese.map(
        item => {
          let testObj = {};
          testObj.city = item.city
          testObj.code = item.code
          finalCityList.push(testObj)
        })
      this.setData({
        completeList: finalCityList,
      })
    } else {
      return
    }
  },
})
